package com.example.myapplication;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;

public class ReviewFragment extends Fragment {

    private RecyclerView recyclerView;
    private ReviewAdapter reviewAdapter;
    private DBHelper dbHelper;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_review, container, false);

        recyclerView = view.findViewById(R.id.recyclerViewReviews);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(),2));

        dbHelper = new DBHelper(getContext());
        loadReviews();

        return view;
    }

    @SuppressLint("Range")
    private void loadReviews() {
        List<Review> reviewList = new ArrayList<>();
        Cursor cursor = dbHelper.getReadableDatabase().rawQuery(
                "SELECT r.review_id, r.rating, r.comment, t.transaction_id, p.name AS product_name " +
                        "FROM reviews r " +
                        "JOIN transactions t ON r.transaction_id = t.transaction_id " +
                        "JOIN products p ON t.product_id = p.product_id", null);

        if (cursor.moveToFirst()) {
            do {
                Review review = new Review();
                review.setReviewId(cursor.getInt(cursor.getColumnIndex("review_id")));
                review.setRating(cursor.getInt(cursor.getColumnIndex("rating")));
                review.setComment(cursor.getString(cursor.getColumnIndex("comment")));
                review.setTransactionId(cursor.getInt(cursor.getColumnIndex("transaction_id")));
                review.setProductName(cursor.getString(cursor.getColumnIndex("product_name")));
                reviewList.add(review);
            } while (cursor.moveToNext());
        }
        cursor.close();

        reviewAdapter = new ReviewAdapter(reviewList, getContext());
        recyclerView.setAdapter(reviewAdapter);
    }
}
